﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.OrderModels;
using CoreShop.PrintService;
using CoreShop.Services;
using CoreShop.Services.Services.System;
using FastMember;
using IWshRuntimeLibrary;
using Loading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.X9;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;
using static CoreShop.Services.PosRemoteServices;

namespace CoreShop.App
{
    public partial class frmMallOrderList : UIForm
    {
        public corecmsordermaster SelectOrderMaster = null;
        public List<corecmsordermaster> orderMasters = new List<corecmsordermaster>();
        OpaqueCommand cmd = new OpaqueCommand();

        public frmMallOrderList()
        {
            InitializeComponent();
            this.dgvOrderList.AutoGenerateColumns = false;
            this.dgvOrderList.DataSource = orderMasters;
            this.ShowFullScreen = AppConstVars.showFullScreen;
            dateTimeRange.DateTimeStar = CommFunc.ConvertToDateTime(DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") + " 00:00:00").ToString("yyyy-MM-dd HH:mm:ss");
            dateTimeRange.DateTimeEnd = CommFunc.ConvertToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59").ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void DoValueChanged(object sender, System.EventArgs e)
        {
            btnRefresh_Click(null,null);
        }

        private void uiButton1_Click(object sender, System.EventArgs e)
        {
            UIButton btn = (UIButton)sender;
            btn.Selected = true;
        }

        private void FOrders_Shown(object sender, System.EventArgs e)
        {
            BindComboBoxData();
            timer1.Start();
        }

        public void BindComboBoxData()
        {
            try
            {
                #region 
                this.checkFlag.Items.Clear();
                var ordertypeList = EnumHelper.EnumToList<GlobalEnumVars.CheckFlag>();
                checkFlag.DataSource = ordertypeList;
                checkFlag.DisplayMember = "description";
                checkFlag.ValueMember = "value";
                if (ordertypeList.Count > 0) this.checkFlag.SelectedIndex = 0;


                this.sourceType.Items.Clear();
                var sourceTypeList = EnumHelper.EnumToList<GlobalEnumVars.FoodOrderSourceType>();
                sourceTypeList = sourceTypeList.OrderBy(p => p.value).ToList();
                sourceType.DataSource = sourceTypeList;
                sourceType.DisplayMember = "description";
                sourceType.ValueMember = "value";
                if (sourceTypeList.Count > 0) this.sourceType.SelectedIndex = 0;

                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void timer1_Tick(object sender, System.EventArgs e)
        {
            timer1.Stop();
            //ShowStatusForm(23);
            Thread.Sleep(100);
            LoadOrderList();
        }

        private void LoadOrderList()
        {
            int? ordertype = null;
            if (this.checkFlag != null) ordertype = CommFunc.ConvertToInt32(this.checkFlag.SelectedValue);

            int? sourceType = null;
            if (this.sourceType != null) sourceType = CommFunc.ConvertToInt32(this.sourceType.SelectedValue);

            DateTime dtStartDate = CommFunc.ConvertToDateTime(dateTimeRange.DateTimeStar);
            DateTime dtEndDate = CommFunc.ConvertToDateTime(dateTimeRange.DateTimeEnd);

            var where = Expressionable.Create<corecmsordermaster>();
            where = where.And(p => p.payTime >= dtStartDate && p.payTime <= dtEndDate);
            if (!string.IsNullOrEmpty(this.strNumber.Text))
            {                
                where = where.And(p => p.orderSn.Contains(this.strNumber.Text));
            }

            if (checkFlag.SelectedValue.ObjToInt() == (int)GlobalEnumVars.CheckFlag.UnCheck)
            {
                where = where.And(p => p.checkFlag == false);
            }
            else
            if (checkFlag.SelectedValue.ObjToInt() == (int)GlobalEnumVars.CheckFlag.Check)
            {
                where = where.And(p => p.checkFlag == true);
            }

            SelectOrderMaster = null;
            
            orderMasters = new corecmsordermasterServices().AsQueryable()
                .Where(where.ToExpression()).OrderBy(p => p.id, OrderByType.Desc).ToList();
            this.dgvOrderList.DataSource = null;
            this.dgvOrderList.DataSource = orderMasters;
            this.sum.Text = orderMasters.Count.ToString();
            this.amount.Text = orderMasters.Sum(p => p.totalAmount).ToString();
            if (orderMasters.Count > 0)
            {
                var masterFirst = orderMasters.First();
                GetSelectOrderMaster(masterFirst.id);
                LoadOrderDetail();
            }

            int myMallOrders = MallOrderUtil.GetOrderCount();
            if (myMallOrders > 0)
                Program.frmOrdering.btnMallOrder.TipsText = myMallOrders.ToString();
            else
                Program.frmOrdering.btnMallOrder.TipsText = "";
        }

        private void BindOrderItemInfo(OrderItemInfo info, corecmsfoodsalemaster item)
        {
            info.Tags.Clear();
            info.id = item.orderId;
            info.paymentId = 0;
            info.Name = item.orderNo.ToString();
            if (!item.isUpload) info.AddTag("未上传");
            info.Order = EnumHelper.GetEnumByValue<GlobalEnumVars.OrderPayStatus>(item.status.ObjToInt(0));
            info.OrderID = item.orderDate.ToString();
            if (item.sourceType == (int)FoodOrderSourceType.Meituan)
                info.OrderID = EnumHelper.GetDescByValue<GlobalEnumVars.FoodOrderSourceType>(item.sourceType.ObjToInt(0));
            info.MoneyFrom = item.sumAllAmount.ToString();
        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetSelectOrderMaster(long orderId)
        {
            SelectOrderMaster = new corecmsordermasterServices().AsQueryable().Where(p => p.id == orderId).First();
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Detail_OnClick(object sender, System.EventArgs e)
        {
            OrderItemInfo itemInfo = (OrderItemInfo)sender;
            SelectOrderMaster = new corecmsordermasterServices().AsQueryable().Where(p => p.id == itemInfo.id).First();
            LoadOrderDetail();
        }

        private void LoadOrderDetail()
        {
            layOrderDetail.Clear();
            if (SelectOrderMaster == null) return;

            try 
            {
                btnSendOrder.Visible = false;
                if (SelectOrderMaster.checkFlag.ObjToBool())
                {
                    btnCheck.Enabled = false;
                    if (!SelectOrderMaster.isUpload) btnSendOrder.Visible = true;
                }                    
                else btnCheck.Enabled = true;      
                
                OnlineOrderModel onlineOrder = SelectOrderMaster.content.JsonToEntity<OnlineOrderModel>(); 

                var orderDetails = onlineOrder.XcxOrderItem;

                btnRefund.Visible = false;
                this.foodInfo.Text = SelectOrderMaster.orderSn + "商品信息";
                this.foodInfoCount.Text = "共" + orderDetails.Count + "项：合计￥" + SelectOrderMaster.totalAmount.ToString();

                this.orderNo.Text = SelectOrderMaster.orderSn;
                this.orderDate.Text = SelectOrderMaster.payTime.ToString();
                this.status.Text = onlineOrder.DispatchingType == "1" ? "待提货" : "待配送"; 
                if (SelectOrderMaster.checkFlag.ObjToBool())
                {
                    this.status.Text = onlineOrder.DispatchingType == "1" ? "已提货" : "已配送"; 
                    onlineOrder.Status = 5;
                }
                this.number.Text = SelectOrderMaster.userPhone.ToString();   
                this.userName.Text = SelectOrderMaster.userName.ToString();
                decimal sumRealAmount = CommFunc.ConvertToDecimal(SelectOrderMaster.totalAmount);
                this.sumRealAmount.Text = sumRealAmount.ToString();//商品价格合计
                this.sumAllAmount.Text = sumRealAmount.ToString();//优惠合计
                lblremaker.Text = onlineOrder.Remark;
                lblStatus.Text = onlineOrder.StatusName;
                lblfreeAmt.Text = onlineOrder.FreeAmount.ToString();
                lbldeliveryChannelName.Text = onlineOrder.deliveryChannelName.ToString();
                lbldeliveryChannelAdd.Text = onlineOrder.XcxOrderLine?.consigneeAddress.ToString();

                if (orderDetails.Count > 0)
                {
                    int rowId = 1;
                    layOrderDetail.Visible = false;
                    foreach (var item in orderDetails)
                    {
                        MenuItemInfo info = new MenuItemInfo();
                        info.Name = item.itemName;
                        info.Count = item.num.ToString();
                        info.Money = "￥" + ((item.ShareAmount != null && CommFunc.ConvertToDecimal(item.ShareAmount) > 0) ? item.ShareAmount : item.salePrice);
                        info.UnitName = item.unit;
                        info.Price = CommFunc.ConvertToDecimal(item.price).ToString("0.0##");
                        info.RealPrice = CommFunc.ConvertToDecimal(item.price).ToString("0.0##");
                        info.Code = item.spuCode;
                        info.IsReturning = false;
                        info.RowId = rowId.ToString();
                        UIMenuItem menu = new UIMenuItem(info);
                        menu.SetMinSize();
                        layOrderDetail.Add(menu);
                        StatusFormStepIt();
                    }
                    layOrderDetail.Visible = true;
                    HideStatusForm();
                }
            }
            catch { }
        }

        private void btnHomePage_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void SetPrint(corecmsordermaster orderMaster)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isPrintRepair, 0)) return;
            OnlineOrderModel onlineOrder = orderMaster.content.JsonToEntity<OnlineOrderModel>();
            new MallOrderPrintServices().SetPrintMallOrder(onlineOrder, isPrintPreview.Checked);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {            
            try
            {
                if (SelectOrderMaster == null)
                {
                    UIMessageBox.Show("请选择一个单据后再打印", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                SetPrint(SelectOrderMaster);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        private void btnSettlementUn_Click(object sender, EventArgs e)
        {
            
        }

        private string GetMenuItemName(long orderingId)
        {
            return "uiMenuItem_" + orderingId.ToString();
        }     

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadOrderList();
        }

        private void dgvFoodList_SelectionChanged(object sender, EventArgs e)
        {
            SelectOrderMaster = null;
            if (dgvOrderList.SelectedRows.Count == 1)
            {
                GetSelectOrderMaster(CommFunc.ConvertToInt64(dgvOrderList.SelectedRows[0].Cells["id"].Value));
            }
            LoadOrderDetail();
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                if (SelectOrderMaster == null)
                {                    
                    UIMessageBox.Show("请选择一个单据后再操作", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                SetOrderCheck(SelectOrderMaster,true);
                btnRefresh.PerformClick();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private async void SetOrderCheck(corecmsordermaster orderMaster,bool isShowMsg)
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                string Msg = "";
                OnlineOrderModel onlineOrder = orderMaster.content.JsonToEntity<OnlineOrderModel>();
                if (isShowMsg) 
                    if (!ShowAskDialog("确认将此订单标记为配送吗？")) return;

                ReturnModel returnModel1 = await OrderApiUtil.UpdateOrderStatus(orderMaster.orderSn, AppConstVars.sysUser);
                if (returnModel1.Status != ReturnStatus.Success)
                {
                    UIMessageBox.Show(returnModel1.MessageOrString);
                    //LogManage.Info($"改变订单状态失败！{returnModel1.MessageOrString}");
                    return;
                }
                onlineOrder.Status = 5;
                //string strMaster = JsonConvert.SerializeObject(onlineOrder);
                new corecmsordermasterServices().Update(a => new corecmsordermaster()
                {
                    checkFlag = true,
                    isUpload = false,
                }, a => a.id == orderMaster.id);
                var postData = await MallOrderUtil.SetUpLoadOrderDataAsync(orderMaster.id);
                
                if (isShowMsg)
                {
                    this.Invoke(new Action(() =>
                    {
                        //刷新数据
                        btnRefresh.PerformClick();
                        SetPrint(orderMaster);
                    }));
                }
                int myMallOrders = MallOrderUtil.GetOrderCount();
                Program.frmOrdering.btnMallOrder.TipsText = myMallOrders.ToString();
            }
            catch (Exception)
            {
                throw;
            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private void btnRefund_Click(object sender, EventArgs e)
        {

        }

        private void btnCheckAll_Click(object sender, EventArgs e)
        {
            foreach (var item in orderMasters)
            {
                if (!item.checkFlag.ObjToBool()) SetOrderCheck(item,false);
            }
            btnRefresh.PerformClick();
        }

        private async void btnSendOrder_ClickAsync(object sender, EventArgs e)
        {
            if (SelectOrderMaster == null)
            {
                UIMessageBox.Show("请选择一个单据后再操作", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            var ret = await MallOrderUtil.SetUpLoadOrderDataAsync(SelectOrderMaster.id);
            if (ret) btnRefresh.PerformClick();
        }
    }
}
